package com.jungle.base.interceptor;

import com.jungle.common.core.domain.model.LoginUser;
import com.jungle.common.helper.LoginHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.modules.db.BoundSql;
import org.ssssssss.magicapi.modules.db.inteceptor.SQLInterceptor;

//@Component
@Slf4j
public class MagicApiPermissionInterceptor implements SQLInterceptor {
    @Override
    public void preHandle(BoundSql boundSql, RequestEntity requestEntity) {
        log.info("这里是 Magic sql拦截器.");
        String sql = boundSql.getSql();
        //查预警数据时只查出用户所在区县的
        if (sql.contains("from yj_yjsjb")) {
            LoginUser loginUser;
            try {
                loginUser = LoginHelper.getLoginUser();
            } catch (NullPointerException e) {
                log.warn(e.getMessage());
                return;
            }
            Long userId = loginUser.getUserId();
            String xzqhbm = loginUser.getAreaCode();
            if (sql.contains("where")) {
                sql = sql.substring(0, sql.indexOf("where") + "where".length()) +
                    " yzqhbm like '" + xzqhbm + "' and " +
                    sql.substring(sql.indexOf("where") + "where".length());
            } else {
                sql = sql.substring(0, sql.indexOf("yj_yjsjb") + "yj_yjsjb".length()) +
                    " where yzqhbm like '" + xzqhbm + "'" +
                    sql.substring(sql.indexOf("yj_yjsjb") + "yj_yjsjb".length());
            }
            log.info("当前用户id:{},所在区县：{},修改后的sql：{}", userId, xzqhbm, sql);
        }
        boundSql.setSql(sql);
    }
}
